import { memo, FC, useState, useEffect, Key } from 'react'
import { Modal, message, Tree } from 'antd'
import { RoleModelState, connect, Dispatch, RoleListType } from 'umi'
import { getTreeData } from '@/utils'

interface IProps {
  visible: boolean
  hide: () => void
  record: RoleListType | undefined
  dispatch: Dispatch
  roleModel: RoleModelState
}

const RoleMenu: FC<IProps> = ({
  visible,
  hide,
  dispatch,
  record,
  roleModel
}) => {
  const [checkedKeys, setCheckedKeys] = useState<Key[]>([])
  const { roleMenu, menuList } = roleModel
  const handleOk = () => {
    dispatch({
      type: 'roleModel/function_saveRoleMenuInfo',
      payload: {
        roleCode: record?.code,
        menuCode: checkedKeys.join(',')
      },
      callback: (response) => {
        if (response.code === 200) {
          message.success('关联菜单成功')
          hide()
        }
      }
    })
  }
  const handleCancel = () => {
    hide()
  }

  //   获取角色菜单信息
  const getRoleMenuInfo = () => {
    dispatch({
      type: 'roleModel/function_getRoleMenuInfo',
      payload: {
        roleCode: record?.code
      }
    })
  }

  const getAllMenuList = () => {
    dispatch({
      type: 'roleModel/function_getMenuList'
    })
  }

  const onCheck = (checkedKeysValue: Key[]) => {
    setCheckedKeys(checkedKeysValue)
  }

  useEffect(() => {
    if (visible) {
      getRoleMenuInfo()
      getAllMenuList()
    }
  }, [visible])

  useEffect(() => {
    const menuCode = roleMenu.map((item) => item.code)
    setCheckedKeys(menuCode)
  }, [roleMenu])
  return (
    <>
      <Modal
        title="角色关联菜单信息"
        open={visible}
        onOk={handleOk}
        onCancel={handleCancel}
        width="40%"
        okText="确认"
        cancelText="取消"
        maskClosable={false}
      >
        {menuList.length && (
          <Tree
            checkable
            defaultExpandAll={true}
            fieldNames={{ title: 'name', key: 'code' }}
            checkedKeys={checkedKeys}
            onCheck={onCheck}
            treeData={getTreeData(menuList)}
          />
        )}
      </Modal>
    </>
  )
}

const mapStateToProps = ({ roleModel }: { roleModel: RoleModelState }) => {
  return {
    roleModel
  }
}

export default connect(mapStateToProps)(memo(RoleMenu))
